<?php
class FileUtil {
  public static function getMimeType($localFilePath) {
    if (!file_exists($localFilePath)) {
      throw new Exception("File($localFilePath) is not found!");
    }

    if (function_exists('finfo_file')) {
      $finfo = finfo_open(FILEINFO_MIME_TYPE);
      $type = finfo_file($finfo, $localFilePath);
      finfo_close($finfo);
    } else if (function_exists('mime_content_type')) {
      //require_once 'upgradephp/ext/mime.php';
      $type = mime_content_type($localFilePath);
    } else {
      $type = false;
    }

    if (!$type || in_array($type, array('application/octet-stream', 'text/plain'))) {
      $secondOpinion = exec('file -b --mime-type ' . escapeshellarg($localFilePath), $foo, $returnCode);
      if ($returnCode === 0 && $secondOpinion) {
        $type = $secondOpinion;
      }
    }

    if (!$type || in_array($type, array('application/octet-stream', 'text/plain'))) {
      //require_once 'upgradephp/ext/mime.php';
      $exifImageType = exif_imagetype($localFilePath);
      if ($exifImageType !== false) {
        $type = image_type_to_mime_type($exifImageType);
      }
    }

    return $type;
  }

  public static function checkImageSize($image, $width, $height) {
    $imageInfo = getimagesize($image);
    if ($imageInfo[0] > $width || $imageInfo[1] > $height) {
      return false;
    }
    return true;
  }
}